package com.zhou.piledriver.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhou.piledriver.mapper.*;
import com.zhou.piledriver.model.dto.MqttHeartbeatDto;
import com.zhou.piledriver.model.dto.MqttRecordDto;
import com.zhou.piledriver.model.entity.*;
import com.zhou.piledriver.service.MqttService;
import com.zhou.piledriver.utils.IdGenerator;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author ZhouShenBin
 * @date 2024/3/20 15:43
 * @description
 */

@Service
@Slf4j
public class MqttServiceImpl implements MqttService {

    @Resource
    PdDeviceMapper pdDeviceMapper;
    @Resource
    PdMachMapper pdMachMapper;
    @Resource
    PdMileageMapper pdMileageMapper;
    @Resource
    PdPileMapper pdPileMapper;
    @Resource
    PdDeviceRecordMapper pdDeviceRecordMapper;


    @Override
    public void handlerHeartbeat(JSONObject jsonObject) {
        MqttHeartbeatDto mqttHeartbeatDto = jsonObject.toBean(MqttHeartbeatDto.class);
        log.info("mqtt心跳包处理：{}", mqttHeartbeatDto);
        PdDevice device = pdDeviceMapper.selectOne(new LambdaQueryWrapper<PdDevice>().eq(PdDevice::getCode, mqttHeartbeatDto.getDev_num()));
        if (Objects.isNull(device)) {
            log.info("设备不存在");
            device = new PdDevice();
            device.setId(IdGenerator.nextId());
            device.setCode(mqttHeartbeatDto.getDev_num());
            pdDeviceMapper.insert(device);
        }
        device.setModel(mqttHeartbeatDto.getDev_model());
        device.setVersion(mqttHeartbeatDto.getDev_ver());
        device.setLongitude(mqttHeartbeatDto.getLng());
        device.setLatitude(mqttHeartbeatDto.getLat());
        device.setRssi(mqttHeartbeatDto.getRssi());
        device.setLatestTime(mqttHeartbeatDto.getTs());
        pdDeviceMapper.updateById(device);
    }

    @Override
    public void handlerRecord(JSONObject jsonObject) throws InterruptedException {
        PdPile pile1, pile2;
        MqttRecordDto mqttRecordDto = jsonObject.toBean(MqttRecordDto.class);
        log.info("mqtt数据包处理：{}", mqttRecordDto);

        PdDevice device = pdDeviceMapper.selectOne(new LambdaQueryWrapper<PdDevice>().eq(PdDevice::getCode, mqttRecordDto.getDevNo()));
        if (Objects.isNull(device)) {
            log.info("设备不存在");
            device = new PdDevice();
            device.setId(IdGenerator.nextId());
            device.setCode(mqttRecordDto.getDevNo());
            pdDeviceMapper.insert(device);
        }
        device.setModel(mqttRecordDto.getDevModel());
        device.setVersion(mqttRecordDto.getDevVer());
        device.setLongitude(mqttRecordDto.getLng());
        device.setLatitude(mqttRecordDto.getLat());
        device.setLatestTime(mqttRecordDto.getTs());
        pdDeviceMapper.updateById(device);

        //处理关联mach
        PdMach mach = pdMachMapper.selectOne(new LambdaQueryWrapper<PdMach>().eq(PdMach::getCode, mqttRecordDto.getMachNo()));
        if (Objects.isNull(mach)) {
            log.info("mach不存在");
            mach = new PdMach();
            mach.setId(IdGenerator.nextId());
            mach.setCode(mqttRecordDto.getMachNo());
            mach.setType(mqttRecordDto.getMachType());
            mach.setDeviceId(device.getId());
            pdMachMapper.insert(mach);
        }
        if(!mach.getDeviceId().equals(device.getId())){
            mach.setDeviceId(device.getId());
        }
        mach.setWorkStatus(mqttRecordDto.getData01().getDataSrcs());
        mach.setPileStatus(mqttRecordDto.getData01().getPileSta());
        pdMachMapper.updateById(mach);

        //处理里程数据
        PdMileage mileage = pdMileageMapper.selectOne(new LambdaQueryWrapper<PdMileage>().eq(PdMileage::getMilNo, mqttRecordDto.getData00().getMilNo()));
        if (Objects.isNull(mileage)) {
            log.info("里程不存在");
            mileage = new PdMileage();
            mileage.setId(IdGenerator.nextId());
            mileage.setMilNo(mqttRecordDto.getData00().getMilNo());
            mileage.setStartTime(mqttRecordDto.getData00().getStartTime());
            pdMileageMapper.insert(mileage);
        }
        if (mqttRecordDto.getData00().getEndTime() != null) {
            mileage.setEndTime(mqttRecordDto.getData00().getEndTime());
        }
        if (!mqttRecordDto.getData01().getPileSta().equals(mileage.getStatus())) {
            mileage.setStatus(mqttRecordDto.getData01().getPileSta());
        }
        pdMileageMapper.updateById(mileage);

        //处理pile数据
        PdDeviceRecord tempRecord = new PdDeviceRecord();
        tempRecord.setDataSource(mqttRecordDto.getData01().getDataSrcs());
        tempRecord.setPileStatus(mqttRecordDto.getData01().getPileSta());
        tempRecord.setAngleX(mqttRecordDto.getData01().getAngelX());
        tempRecord.setAngleY(mqttRecordDto.getData01().getAngelY());
        tempRecord.setVert(mqttRecordDto.getData01().getVert());
        tempRecord.setDensity(mqttRecordDto.getData01().getDensity());
        tempRecord.setSpeed(mqttRecordDto.getData01().getSpeed());
        tempRecord.setPileDepth(mqttRecordDto.getData01().getPileDepth());
        tempRecord.setFirDepth(mqttRecordDto.getData01().getFirDepth());
        tempRecord.setSecDepth(mqttRecordDto.getData01().getSecDepth());
        tempRecord.setEmDepth(mqttRecordDto.getData01().getEmDepth());
        tempRecord.setCurDepth(mqttRecordDto.getData01().getCurDepth());
        tempRecord.setSlurSta(mqttRecordDto.getData01().getSlurSta());
        //暂时将入库时间改为系统时间，用于数据测试
//        tempRecord.setDataTime(mqttRecordDto.getTs());
        tempRecord.setDataTime(LocalDateTime.now());

        if (!Objects.isNull(mqttRecordDto.getData00().getPileNo1())) {
            pile1 = pdPileMapper.selectOne(new LambdaQueryWrapper<PdPile>()
                    .eq(PdPile::getPileNo, mqttRecordDto.getData00().getPileNo1())
                    .eq(PdPile::getMilId, mileage.getId())
                    .eq(PdPile::getDeviceCode, mqttRecordDto.getDevNo())
                    .eq(PdPile::getMachCode, mqttRecordDto.getMachNo()));
            if (Objects.isNull(pile1)) {
                log.info("pile1不存在");
                pile1 = new PdPile();
                pile1.setId(IdGenerator.nextId());
                pile1.setPileNo(mqttRecordDto.getData00().getPileNo1());
                pile1.setMilId(mileage.getId());
                pile1.setMilNo(mqttRecordDto.getData00().getMilNo());
                pile1.setDeviceCode(mqttRecordDto.getDevNo());
                pile1.setMachCode(mqttRecordDto.getMachNo());
                pile1.setRowNo(mqttRecordDto.getData00().getRowNo1());
                pdPileMapper.insert(pile1);
            }

            PdDeviceRecord deviceRecord1 = new PdDeviceRecord();
            BeanUtils.copyProperties(tempRecord, deviceRecord1, "id");
            deviceRecord1.setId(IdGenerator.nextId());
            deviceRecord1.setPileId(pile1.getId());
            deviceRecord1.setPileNo(pile1.getPileNo());
            deviceRecord1.setCur(mqttRecordDto.getData01().getCur1());
            deviceRecord1.setPressure(mqttRecordDto.getData01().getPressure1());
            deviceRecord1.setFlow(mqttRecordDto.getData01().getFlow1());
            deviceRecord1.setSegAsh(mqttRecordDto.getData01().getSegAsh1());
            deviceRecord1.setEmSlur(mqttRecordDto.getData01().getEmSlur1());
            deviceRecord1.setEmAsh(mqttRecordDto.getData01().getEmAsh1());

            pdDeviceRecordMapper.insert(deviceRecord1);
        }

        if (!Objects.isNull(mqttRecordDto.getData00().getPileNo2())) {
            pile2 = pdPileMapper.selectOne(new LambdaQueryWrapper<PdPile>()
                    .eq(PdPile::getPileNo, mqttRecordDto.getData00().getPileNo2())
                    .eq(PdPile::getMilId, mileage.getId())
                    .eq(PdPile::getDeviceCode, mqttRecordDto.getDevNo())
                    .eq(PdPile::getMachCode, mqttRecordDto.getMachNo()));
            if (Objects.isNull(pile2)) {
                log.info("pile2不存在");
                pile2 = new PdPile();
                pile2.setId(IdGenerator.nextId());
                pile2.setPileNo(mqttRecordDto.getData00().getPileNo2());
                pile2.setMilId(mileage.getId());
                pile2.setMilNo(mqttRecordDto.getData00().getMilNo());
                pile2.setDeviceCode(mqttRecordDto.getDevNo());
                pile2.setMachCode(mqttRecordDto.getMachNo());
                pile2.setRowNo(mqttRecordDto.getData00().getRowNo2());
                pdPileMapper.insert(pile2);
            }
            PdDeviceRecord deviceRecord2 = new PdDeviceRecord();
            BeanUtils.copyProperties(tempRecord, deviceRecord2, "id");
            deviceRecord2.setPileId(pile2.getId());
            deviceRecord2.setPileNo(pile2.getPileNo());
            deviceRecord2.setCur(mqttRecordDto.getData01().getCur2());
            deviceRecord2.setPressure(mqttRecordDto.getData01().getPressure2());
            deviceRecord2.setFlow(mqttRecordDto.getData01().getFlow2());
            deviceRecord2.setSegAsh(mqttRecordDto.getData01().getSegAsh2());
            deviceRecord2.setEmSlur(mqttRecordDto.getData01().getEmSlur2());
            deviceRecord2.setEmAsh(mqttRecordDto.getData01().getEmAsh2());

            pdDeviceRecordMapper.insert(deviceRecord2);
        }

    }
}
